package com.baoteng.rbspy.vo;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

public class JsonLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>{

	@Override
	public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		 JsonNode node = p.getCodec().readTree(p);
		 node.getNodeType();
		 switch(node.getNodeType()){
		 case STRING:
			 String dateStr = node.textValue();
			 if(StringUtils.isBlank(dateStr)){
				 return null;
			 }
			 String value = dateStr.trim();
			 if(dateStr.matches("^\\d{4}-\\d{1,2}$")){ 
		            try {
						return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM"));
					} catch (DateTimeParseException  e) {
						e.printStackTrace();
						return null;
					}
		        }else if(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
		        	try {
		        		return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
					} catch (DateTimeParseException  e) {
						e.printStackTrace();
						return null;
					}
		        }else if(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
		        	try {
						return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm"));
					} catch (DateTimeParseException  e) {
						e.printStackTrace();
						return null;
					}
		        }else if(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
		            try {
		            	return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
					} catch (DateTimeParseException  e) {
						e.printStackTrace();
					}
		        }
			 break;
		default:
			break;
		 }
		 return LocalDateTime.now();
	}
	 	
}
